<template>
  <div class="order-list-component">
    <el-tabs v-model="activeStatus" @tab-click="handleStatusChange">
      <el-tab-pane label="全部" name="all" />
      <el-tab-pane label="待付款" name="pending" />
      <el-tab-pane label="待发货" name="paid" />
      <el-tab-pane label="待收货" name="shipped" />
      <el-tab-pane label="已完成" name="completed" />
      <el-tab-pane label="已取消" name="cancelled" />
    </el-tabs>

    <!-- 订单列表 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <div v-else-if="orders.length === 0" class="empty-container">
      <el-empty description="暂无订单">
        <el-button type="primary" @click="goToHome">去购物</el-button>
      </el-empty>
    </div>

    <div v-else class="orders-container">
      <div v-for="order in orders" :key="order.orderId" class="order-item">
        <!-- 订单头部 -->
        <div class="order-header">
          <div class="order-info">
            <span class="order-number">订单号：{{ order.orderNumber }}</span>
            <span class="order-date">{{ formatDate(order.createdAt) }}</span>
          </div>
          <div class="order-status">
            <el-tag :type="getStatusType(order.status) as any">
              {{ getStatusText(order.status) }}
            </el-tag>
          </div>
        </div>

        <!-- 订单商品 -->
        <div class="order-products">
          <div
            v-for="item in order.items"
            :key="item.orderItemId"
            class="product-item"
            @click="goToProduct(item.productId)"
          >
            <el-image
              :src="item.productImage"
              :alt="item.productName"
              class="product-image"
              fit="cover"
            />
            <div class="product-info">
              <h4 class="product-name">{{ item.productName }}</h4>
              <p class="product-spec">
                {{ item.sku }} / 数量：{{ item.quantity }}
              </p>
              <p class="product-price">¥{{ item.price }}</p>
            </div>
          </div>
        </div>

        <!-- 订单备注 -->
        <div v-if="order.remark" class="order-remark">
          <el-tag type="info" size="small">
            <i class="el-icon-edit"></i>
            备注：{{ order.remark }}
          </el-tag>
        </div>

        <!-- 订单底部 -->
        <div class="order-footer">
          <div class="order-total">
            <span>共 {{ getTotalQuantity(order.items) }} 件商品</span>
            <span class="total-amount">总计：¥{{ order.finalTotal }}</span>
          </div>
          <div class="order-actions">
            <el-button
              v-if="order.status === 'PENDING_PAYMENT'"
              type="primary"
              @click="payOrder(order.orderId)"
            >
              立即付款
            </el-button>
            <el-button
              v-if="order.status === 'SHIPPED'"
              type="success"
              @click="confirmReceive(order.orderId)"
            >
              确认收货
            </el-button>
            <el-button v-if="order.status === 'PENDING_PAYMENT'" @click="cancelOrder(order.orderId)">
              取消订单
            </el-button>
            <el-button @click="viewOrderDetail(order.orderId)"> 查看详情 </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="totalPages > 1" class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { orderService } from '@/api/orderService'
import type { Order, OrderItem, OrderStatus } from '@/types'

// Props
interface Props {
  userId?: number // 可选的用户ID，如果不传则使用当前登录用户
  showHeader?: boolean // 是否显示页面标题
  compact?: boolean // 是否使用紧凑模式
}

const props = withDefaults(defineProps<Props>(), {
  showHeader: false,
  compact: false
})

// Emits
const emit = defineEmits<{
  orderClick: [orderId: number]
  orderAction: [action: string, orderId: number]
}>()

const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const orders = ref<Order[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const activeStatus = ref('all')

// 计算属性
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

// 状态映射
const statusToNumber: Record<string, number> = {
  all: -1,
  pending: 0,
  paid: 1,
  shipped: 2,
  completed: 3,
  cancelled: 4,
  refund_applied: 5,
  refunded: 6,
  failed: 7, // 支付失败
  expired: 8, // 订单过期
}

const numberToStatus: Record<number, string> = {
  0: 'PENDING_PAYMENT',
  1: 'PAID',
  2: 'SHIPPED',
  3: 'COMPLETED',
  4: 'CANCELLED',
  5: 'REFUND_APPLIED',
  6: 'REFUNDED',
  7: 'FAILED', // 支付失败
  8: 'EXPIRED', // 订单过期
}

// 添加字符串状态到数字状态的映射
const stringToNumber: Record<string, number> = {
  'PENDING_PAYMENT': 0,
  'PAID': 1,
  'SHIPPED': 2,
  'COMPLETED': 3,
  'CANCELLED': 4,
  'REFUND_APPLIED': 5,
  'REFUNDED': 6,
  'FAILED': 7, // 支付失败
  'EXPIRED': 8, // 订单过期
}

// 后端订单数据结构类型定义
interface BackendOrderItem {
  itemId: number
  orderId: number
  shoeId: number
  productSku: string
  productName: string
  productImage: string
  productPrice: number | string
  quantity: number
  totalPrice: number | string
}

interface BackendOrder {
  orderId: number
  orderSn: string
  userId: number
  totalAmount: number | string
  payAmount: number | string
  status: number | string // 支持数字和字符串状态
  receiverName: string
  receiverPhone: string
  receiverAddress: string
  remark?: string
  createdAt: string
  updatedAt: string
  statusDesc?: string
  orderItems: BackendOrderItem[]
}

// 数据映射
const mapBackendOrderToView = (o: BackendOrder): Order => {
  console.log('🔍 映射后端订单数据:', {
    orderId: o.orderId,
    status: o.status,
    statusType: typeof o.status,
    statusDesc: o.statusDesc
  })
  
  const viewItems: OrderItem[] = (o.orderItems || []).map((it: BackendOrderItem) => ({
    orderItemId: it.itemId,
    orderId: it.orderId,
    productId: it.shoeId,
    productName: it.productName,
    productImage: it.productImage,
    quantity: it.quantity,
    price: Number(it.productPrice),
    sku: it.productSku,
    subtotal: Number(it.totalPrice),
  }))
  
  // 状态映射：将数字状态转换为字符串状态
  let mappedStatus: OrderStatus
  if (typeof o.status === 'string') {
    // 如果是字符串状态，尝试转换为数字状态再转换为标准字符串状态
    const statusNumber = stringToNumber[o.status]
    if (statusNumber !== undefined) {
      mappedStatus = numberToStatus[statusNumber] as OrderStatus
    } else {
      // 如果字符串状态不在映射中，使用默认状态
      mappedStatus = 'PENDING_PAYMENT'
    }
  } else {
    // 如果是数字状态，转换为标准字符串状态
    mappedStatus = (numberToStatus[o.status] as OrderStatus) || 'PENDING_PAYMENT'
  }
  
  console.log('🔍 状态映射结果:', {
    originalStatus: o.status,
    mappedStatus: mappedStatus
  })
  
  return {
    orderId: o.orderId,
    orderNumber: o.orderSn,
    userId: o.userId,
    addressId: 0,
    productTotal: 0,
    shippingFee: 0,
    finalTotal: Number(o.payAmount ?? o.totalAmount ?? 0),
    status: mappedStatus,
    paymentStatus: 'PAID',
    paymentMethod: '',
    shippingMethod: '',
    remark: o.remark || undefined,
    createdAt: o.createdAt,
    updatedAt: o.updatedAt,
    items: viewItems,
    address: undefined,
  }
}

// 获取订单数据
const fetchOrders = async () => {
  loading.value = true
  try {
    const targetUserId = props.userId || authStore.user?.id
    console.log('🔍 调试订单获取:', {
      propsUserId: props.userId,
      authStoreUser: authStore.user,
      targetUserId,
      isAuthenticated: authStore.isAuthenticated,
      userRole: authStore.userRole
    })
    
    if (!targetUserId) {
      console.warn('⚠️ 没有用户ID，无法获取订单')
      orders.value = []
      total.value = 0
      return
    }
    
    console.log('📡 开始调用订单API，用户ID:', targetUserId)
    const resp = await orderService.getUserOrders(targetUserId)
    console.log('📡 订单API响应:', resp)
    
    const allOrders = Array.isArray(resp.data.data) ? resp.data.data : []
    console.log('📦 解析后的订单数据:', allOrders)
    
    let mapped: Order[] = allOrders.map((order: unknown) => mapBackendOrderToView(order as BackendOrder))
    console.log('🔄 映射后的订单数据:', mapped)

    // 按状态筛选
    if (activeStatus.value !== 'all') {
      const want = statusToNumber[activeStatus.value]
      mapped = mapped.filter((ord) => {
        // 将字符串状态转换为数字状态进行筛选
        let statusCode: number
        if (typeof ord.status === 'string') {
          // 从字符串状态反向查找数字状态
          const found = Object.entries(numberToStatus).find(([, v]) => v === ord.status)
          statusCode = found ? Number(found[0]) : -1
        } else {
          statusCode = ord.status as number
        }
        return statusCode === want
      })
      console.log('🔍 状态筛选后的订单:', mapped)
    }

    // 分页
    total.value = mapped.length
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    orders.value = mapped.slice(start, end)
    console.log('📄 分页后的订单:', orders.value)
  } catch (error) {
    console.error('❌ 获取订单列表失败:', error)
    ElMessage.error('订单加载失败，请稍后重试')
    orders.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 事件处理
const handleStatusChange = () => {
  currentPage.value = 1
  fetchOrders()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchOrders()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchOrders()
}

// 工具方法
const getStatusType = (status: string | number) => {
  console.log('🔍 获取状态类型，输入状态:', status, '类型:', typeof status)
  
  // 直接处理数字状态
  if (typeof status === 'number') {
    const statusMap: Record<number, string> = {
      0: 'warning', // 待付款
      1: 'info',    // 待发货
      2: 'primary', // 运输中
      3: 'success', // 已完成
      4: 'danger',  // 已取消
      5: 'warning', // 申请退货
      6: 'info',    // 已退货
      7: 'danger',  // 支付失败
      8: 'info',    // 订单过期
    }
    const result = statusMap[status] || 'info'
    console.log('🔍 数字状态类型映射结果:', result)
    return result
  }
  
  // 处理字符串状态
  const statusMap: Record<string, string> = {
    'PENDING_PAYMENT': 'warning',
    'PAID': 'info',
    'SHIPPED': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'danger',
    'REFUND_APPLIED': 'warning',
    'REFUNDED': 'info',
    'FAILED': 'danger',
    'EXPIRED': 'info',
    // 兼容旧的状态名称
    'pending': 'warning',
    'paid': 'info',
    'shipped': 'primary',
    'completed': 'success',
    'cancelled': 'danger',
    'refund_applied': 'warning',
    'refunded': 'info',
    'failed': 'danger',
    'expired': 'info',
  }
  
  const result = statusMap[status] || 'info'
  console.log('🔍 字符串状态类型映射结果:', result)
  return result
}

const getStatusText = (status: string | number) => {
  console.log('🔍 获取状态文本，输入状态:', status, '类型:', typeof status)
  
  // 直接处理数字状态
  if (typeof status === 'number') {
    const statusMap: Record<number, string> = {
      0: '待付款',
      1: '待发货',
      2: '运输中',
      3: '已完成',
      4: '已取消',
      5: '申请退货',
      6: '已退货',
      7: '支付失败',
      8: '订单过期',
    }
    const result = statusMap[status] || '未知状态'
    console.log('🔍 数字状态映射结果:', result)
    return result
  }
  
  // 处理字符串状态
  const statusMap: Record<string, string> = {
    'PENDING_PAYMENT': '待付款',
    'PAID': '待发货',
    'SHIPPED': '运输中',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消',
    'REFUND_APPLIED': '申请退货',
    'REFUNDED': '已退货',
    'FAILED': '支付失败',
    'EXPIRED': '订单过期',
    // 兼容旧的状态名称
    'pending': '待付款',
    'paid': '待发货',
    'shipped': '运输中',
    'completed': '已完成',
    'cancelled': '已取消',
    'refund_applied': '申请退货',
    'refunded': '已退货',
    'failed': '支付失败',
    'expired': '订单过期',
  }
  
  const result = statusMap[status] || '未知状态'
  console.log('🔍 字符串状态映射结果:', result)
  return result
}

const formatDate = (date: string | Date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

const getTotalQuantity = (items: OrderItem[]) => {
  return items.reduce((total, item) => total + item.quantity, 0)
}

// 订单操作
const payOrder = (orderId: number) => {
  emit('orderAction', 'pay', orderId)
  router.push({
    path: '/payment',
    query: { orderId }
  })
}

const confirmReceive = async (orderId: number) => {
  try {
    await ElMessageBox.confirm('确认已收到商品？', '确认收货', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })

    emit('orderAction', 'confirmReceive', orderId)
    // TODO: 调用确认收货API
    await orderService.updateOrderStatus(orderId, 3)

    ElMessage.success('确认收货成功')
    fetchOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('确认收货失败')
    }
  }
}

const cancelOrder = async (orderId: number) => {
  try {
    await ElMessageBox.confirm('确认取消订单？', '取消订单', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // 调用取消订单API（后端已集成库存恢复逻辑）
    try {
      const cancelResult = await orderService.cancelOrder(orderId)
      
      if (cancelResult && cancelResult.status === 200) {
        ElMessage.success('订单取消成功')
        emit('orderAction', 'cancel', orderId)
        // 刷新订单列表
        await fetchOrders()
      } else {
        ElMessage.error('取消订单失败')
      }
    } catch (e) {
      console.error('调用取消订单API失败:', e)
      ElMessage.error('取消订单失败，请重试')
      return
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error(error.message || '取消订单失败')
    }
  }
}

const reviewOrder = (orderId: number) => {
  emit('orderAction', 'review', orderId)
  router.push(`/order/${orderId}/review`)
}

const viewOrderDetail = (orderId: number) => {
  emit('orderClick', orderId)
  router.push(`/order/${orderId}`)
}

const goToProduct = (productId: number) => {
  router.push(`/product/${productId}`)
}

const goToHome = () => {
  router.push('/')
}

// 监听props变化
watch(() => props.userId, () => {
  fetchOrders()
})

// 暴露方法给父组件
defineExpose({
  fetchOrders,
  refresh: fetchOrders
})

// 组件挂载时获取数据
onMounted(() => {
  console.log('🔍 OrderListComponent 挂载，检查认证状态:', {
    isAuthenticated: authStore.isAuthenticated,
    user: authStore.user,
    admin: authStore.admin,
    token: authStore.token,
    localStorage: {
      token: localStorage.getItem('token'),
      user: localStorage.getItem('user'),
      userType: localStorage.getItem('userType')
    }
  })
  fetchOrders()
})

// 测试状态映射函数
const testStatusMapping = () => {
  console.log('🧪 测试状态映射函数')
  
  // 测试数字状态
  const testNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8]
  testNumbers.forEach(status => {
    console.log(`状态 ${status}:`, {
      text: getStatusText(status),
      type: getStatusType(status)
    })
  })
  
  // 测试字符串状态
  const testStrings = ['PENDING_PAYMENT', 'PAID', 'SHIPPED', 'COMPLETED', 'CANCELLED']
  testStrings.forEach(status => {
    console.log(`状态 "${status}":`, {
      text: getStatusText(status),
      type: getStatusType(status)
    })
  })
}

// 在开发环境下自动测试
if (import.meta.env.DEV) {
  setTimeout(testStatusMapping, 1000)
}
</script>

<style scoped>
.order-list-component {
  width: 100%;
}

.filter-section {
  margin-bottom: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.loading-container {
  padding: 40px 0;
}

.empty-container {
  padding: 60px 0;
}

.orders-container {
  margin-bottom: 32px;
}

.order-item {
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.order-number {
  font-weight: 600;
  color: #303133;
}

.order-date {
  font-size: 14px;
  color: #909399;
}

.order-products {
  padding: 20px;
}

.product-item {
  display: flex;
  gap: 16px;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.product-item:last-child {
  border-bottom: none;
}

.product-item:hover {
  background-color: #f8f9fa;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0 0 8px 0;
}

.product-spec {
  font-size: 14px;
  color: #606266;
  margin: 0 0 8px 0;
}

.product-price {
  font-size: 16px;
  font-weight: 600;
  color: #e6a23c;
  margin: 0;
}

.order-remark {
  padding: 16px 20px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
  border-bottom: 1px solid #e9ecef;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
}

.order-total {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 14px;
  color: #606266;
}

.total-amount {
  font-size: 18px;
  font-weight: 600;
  color: #e6a23c;
}

.order-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

/* 紧凑模式样式 */
.order-list-component.compact .order-item {
  margin-bottom: 12px;
}

.order-list-component.compact .order-header,
.order-list-component.compact .order-footer {
  padding: 12px 16px;
}

.order-list-component.compact .order-products {
  padding: 16px;
}

.order-list-component.compact .product-item {
  padding: 12px 0;
}

.order-list-component.compact .product-image {
  width: 60px;
  height: 60px;
}
</style>
